<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

function mySortVisitor($a,$b){
    if ($a['created']==$b['created']) return 0;
    return ($a['created']<$b['created'])?1:-1;
}

class visitorCon extends rootCon
{
    //访客,目前一个管理员只能创建一个机构
    public function listAction() {
        $uid = mylogin::getUid(true);

        $trace = new Visitor();
        //找到当前用户对应的机构id
        if(r('isDebug')) {
            $schoolId = 1;
            $sql = "SELECT * FROM ".$trace->table()." WHERE schoolId=".$schoolId;
        }else if(r('type')=='schoolAdmin'){
            $school = new School();
            $school->uid= $uid;
            $school->addFrom = 2;//通过管理端上传的机构
          //  $school->status = STATUS_PUBLISH;
            $find = $school->find('uid='.$uid." AND addFrom!=1 ");
            if(!$find){
                $this->j(-1,"没有找到通过审核的机构",['uid'=>$uid,'con'=>$school->getConByLoad()]);
            }
            $schoolId = $school->schoolId;
            $sql = "SELECT * FROM ".$trace->table()." WHERE schoolId=".$schoolId;
        }else if(r('type')=='teacher'){
            $teacher = new Teacher();
            $find = $teacher->find(['uid'=>$uid,'status'=>STATUS_PUBLISH]);
            if(!$find){
                $this->j(-2,'您没有通过审核的老师身份',['uid'=>$uid]);
            }
            $teacherId = intval($teacher->teacherId);

            //检查这个老师，有哪些课程
            $sql = "SELECT * FROM ".$trace->table()." WHERE teacherId=$teacherId";
        }else{
            $this->j(-1,'参数错了',['type'=>r('type')]);
        }

        //将最新的访问用户记录到数据库
        $rect = $trace->pager($sql." GROUP BY uid ",20,"visitorId DESC");
        $i = 0;
        $updatedUid = [];
        foreach($rect['list'] as $item){
            $uid = intval($item['uid']);
            $tmpObj = new Visitor();
            $tmpSql = $sql." AND uid=$uid ORDER BY updated DESC LIMIT 1";
            $one = $tmpObj->one($tmpSql);
            if(!$one) continue;
            $rect['list'][$i] = $one;

            if(!$item['avatar']){
                $user = new User();
                $user->find($uid);
                if($user->avatar){
                    $rect['list'][$i]['avatar'] = $user->avatar;
                    $rect['list'][$i]['nick'] = $user->nick;

                    if(!in_array($uid,$updatedUid)){
                        $v = new Visitor();
                        $vSql = "UPDATE ".$v->table()." SET nick='{$user->nick}',avatar='{$user->avatar}' WHERE uid=$uid";
                        $v->query($vSql);
                        $updatedUid[] = $uid;
                    }
                    
                }else{
                    $rect['list'][$i]['avatar'] = FRONT_URL."/default.png";
                }
            
            }else{
                $rect['list'][$i]['avatar'] = FRONT_URL.$item['avatar'];
            }

            if(!$item['nick']){
                $rect['list'][$i]['nick'] = "访客";
            }

            $time = strtotime($rect['list'][$i]['created']);
            $rect['list'][$i]['month'] = date('m',$time);
            $rect['list'][$i]['day'] = date('d',$time);

            $i++;
        }//end foreach

        usort($rect['list'],"mySortVisitor");
        $this->j(0, '请求成功' ,$rect);

        }
    
    private function getCourseStrByTeacher($teacherId){
         //检查这个老师，有哪些课程
         $teacherCourse = new CourseTeacher();
         $teacherCourse->teacherId = $teacherId;
         $teacherCourse->status = STATUS_PUBLISH;
         $all = $teacherCourse->findAll();
         $i = 0;
         $courseIds = [-1];
         foreach($all as $item){
             $courseIds[] = $item['courseId'];
             $i++;
         }
         $courseStr = join(",",$courseIds);
         return $courseStr;
    }

    //访客详情
    public function infoAction(){
        $uid = mylogin::getUid(true);

        //访客id
        $visitorUid = r_int('visitorUid');
        if(r('isDebug')) $visitorUid = 1;

        $type = r('type');
        //找到当前用户对应的机构id
        if(r('isDebug')) {
            $schoolId = 1;
        }else if($type=='schoolAdmin'){
            $schoolAdmin = new SchoolAdmin();
            $schoolAdmin->uid= $uid;
            $schoolAdmin->status = STATUS_PUBLISH;
            $find = $schoolAdmin->find();
            if(!$find){
                $this->j(-1,"没有找到通过审核的机构",['uid'=>$uid]);
            }
            $schoolId = $schoolAdmin->schoolId;
        }else if($type=='teacher'){
            $teacher = new Teacher();
            $teacher->status= STATUS_PUBLISH;
            $find = $teacher->find(['uid'=>$uid]);
            $teacherId = intval($teacher->teacherId);
            if(!$find){
                $this->j(-2,"没有找到通过审核的老师");
            }
            
            //检查这个老师，有哪些课程
            $courseStr = $this->getCourseStrByTeacher($teacherId);
        }else{
            $this->j(-1,"类型错误",['type'=>$type]);
        }



        $user = new User();
        $user->find($visitorUid);
        $rec['uid']      = $user->uid;
        $rec['nick']     = $user->nick;
        $rec['avatar']   = $user->avatar;
        if(!preg_match("/^http/i",$rec['avatar'])){
            $rec['avatar']  = FRONT_URL.$rec['avatar'];
        }

        if($type=='schoolAdmin'){
            //获取访问记录
            $trace = new Visitor();
            $trace->find(['uid'=>$visitorUid,"schoolId"=>$schoolId],$trace->key()." ASC");
            $rec['firstTime'] = $trace->created;

            $trace->find(['uid'=>$visitorUid,"schoolId"=>$schoolId],$trace->key()." DESC");
            $rec['lastTime'] = $trace->created;

            $sql = "SELECT COUNT(1) AS NUM FROM ".$trace->table()." WHERE schoolId=".$schoolId." AND uid=$visitorUid";
            $row = $trace->getOne($sql);
            $rec['visitCount'] = $row['NUM'];

            //统计
            $visitor = new Visitor();
            $sql = "SELECT COUNT(1) AS NUM,courseId FROM ".$visitor->table()." WHERE schoolId=".$schoolId." AND courseId>0 AND uid=$visitorUid GROUP BY courseId ORDER BY NUM DESC LIMIT 1";
            $row = $visitor->getOne($sql);

            //访问记录
            $sqlList = "SELECT * FROM ".$visitor->table()." WHERE uid=$visitorUid AND schoolId=".$schoolId;
        }else{//teacher
            $trace = new Visitor();
            $sql = "SELECT * FROM ".$trace->table()." WHERE uid=$visitorUid AND (courseId IN ($courseStr) OR teacherId=$teacherId) ORDER BY ".$trace->key()." ASC LIMIT 1";
            $one = $trace->one($sql);
            $rec['firstTime'] = $one['created'];

            $sql = "SELECT * FROM ".$trace->table()." WHERE uid=$visitorUid AND (courseId IN ($courseStr)  OR teacherId=$teacherId) ORDER BY ".$trace->key()." DESC LIMIT 1";
            $one = $trace->one($sql);
            $rec['lastTime'] = $one['created'];

            $sql = "SELECT COUNT(1) AS NUM FROM ".$trace->table()." WHERE uid=$visitorUid AND (courseId IN ($courseStr)  OR teacherId=$teacherId) ";
            $row = $trace->getOne($sql);
            $rec['visitCount'] = $row['NUM'];

             //统计
             $visitor = new Visitor();
             $sql = "SELECT COUNT(1) AS NUM,courseId FROM ".$visitor->table()." WHERE uid=$visitorUid AND (courseId IN ($courseStr)  OR teacherId=$teacherId)  GROUP BY courseId ORDER BY NUM DESC LIMIT 1";
             $row = $visitor->getOne($sql);

             //访问记录
             $sqlList = "SELECT * FROM ".$visitor->table()." WHERE uid=$visitorUid AND  ((courseId IN ($courseStr)  OR teacherId=$teacherId) )";
        }
        
        $rec['favorCourseId'] = $row['courseId'];
        $course = new Course();
        $course->find($row['courseId']);
        if(!$course->courseName) $course->courseName = '暂无';
        $rec['favorCourseName'] = $course->courseName;
        if(IS_DEBUG) $rec['sql']=$sql;


        $visitor = new Visitor();
        $rec['visitorList'] = $visitor->pager($sqlList);
        $i = 0;
        foreach($rec['visitorList']['list'] as $item){
            $time = strtotime($item['created']);
            $rec['visitorList']['list'][$i]['month'] = date('m',$time );
            $rec['visitorList']['list'][$i]['day'] = date('d',$time );
            $i++;
        }


        $this->j(0,$rec);
    }

    public function enterAction(){
        $uid = mylogin::getUid(true);
        $visitor = new Visitor();
        $visitor->load();
        $visitor->uid = $uid;
        $user = new User();
        $user->find($uid);
        $visitor->avatar = $user->avatar;
        $visitor->nick = $user->nick;

        $visitor->ip = myrequest::getIP();
        $visitor->ipInfo = myip::getAddresInfo($visitor->ip);
        $visitor->created = date('Y-m-d H:i:s');
        $visitor->save();
        $this->j(0,'',['visitorId'=>$visitor->visitorId]);
    }

    public function leaveAction(){
        $uid = mylogin::getUid(true);
        $visitor = new Visitor();
        $visitor->load();
        $visitor->find();
        if($visitor->uid != $uid){
            $this->j(-1,'用户ID错误');
        }

        $visitor->leaveTime = date('Y-m-d H:i:s');
        $visitor->duration = strtotime($visitor->leaveTime) - strtotime($visitor->created);
        $visitor->save();
        $this->j(0,'',['visitorId'=>$visitor->visitorId,'leaveTime'=>$visitor->leaveTime]);
    }
}



